<template>
  <div class="detail">
    <el-form
      ref="postForm"
      :model="postForm"
      :rules="rules"
      label-position="right"
      label-width="100px"
    >
      <div class="form-data">
        <el-form-item label="角色标题" prop="title">
          <el-input
            v-model="postForm.title"
            placeholder="角色标题"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="角色名称" prop="name">
          <el-input
            v-model="postForm.name"
            placeholder="角色名称"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="角色状态" prop="status">
          <el-switch
            v-model.number="postForm.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="角色菜单" prop="menus">
          <el-container style="height:300px">
            <el-main>
              <el-tree
                ref="menuTree"
                :data="menuTreeData"
                show-checkbox
                node-key="id"
                highlight-current
                default-expand-all
                :default-checked-keys="postForm.menus"
                :render-content="renderTreeContent"
              />
            </el-main>
          </el-container>
        </el-form-item>
        <el-form-item label="权限规则" prop="rules">
          <el-container style="height:300px">
            <el-main>
              <el-tree
                ref="ruleTree"
                :data="ruleTreeData"
                show-checkbox
                node-key="id"
                highlight-current
                default-expand-all
                :default-checked-keys="postForm.rules"
                :render-content="renderTreeContent"
              />
            </el-main>
          </el-container>
        </el-form-item>
      </div>

      <sticky :class-name="'sub-navbar'">
        <el-button
          v-loading="loading"
          type="success"
          style="margin-left: 10px"
          @click="submitForm"
        >
          {{ isEdit ? '编辑' : '添加' }}
        </el-button>
      </sticky>

    </el-form>
  </div>
</template>

<script>
import Sticky from '@/components/Sticky'
import { addAuthRole, editAuthRole, getAuthRoleByID } from '@/api/auth-role'
import { getMenuElementTreeData } from '@/api/auth-menu'
import { getRuleElementTreeData } from '@/api/auth-rule'

const fields = {
  title: '标题',
  name: '名称'
}

export default {
  name: 'AuthRoleDetail',
  components: { Sticky },
  props: {
    id: {
      type: Number,
      default: 0
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (!value || value === '' || value.trim() === '') {
        const errMsg = fields[rule.field] + '为必填项'
        callback(new Error(errMsg))
      } else {
        callback()
      }
    }
    return {
      isEdit: false,
      loading: false,
      menuTreeData: [],
      ruleTreeData: [],
      postForm: {
        title: '',
        name: '',
        status: 1,
        menus: [],
        rules: []
      },
      rules: {
        title: [
          { required: true, message: '标题不能为空' },
          { validator: validateRequire, trigger: 'blur' }
        ],
        name: [
          { required: true, message: '名称不能为空' },
          { validator: validateRequire, trigger: 'blur' }
        ],
        status: [
          { required: true, message: '状态不能为空' },
          { type: 'number', message: '状态值格式不正确' }
        ]
      }
    }
  },
  watch: {
    // id(val) {
    //   this.id = val
    //   this.getRoleByID()
    // }
  },
  // created() {
  //   this.$on('opened', () => {
  //     this.getRoleByID()
  //   })
  //   // this.getRoleByID()
  // },
  methods: {
    submitForm() {
      if (!this.loading) {
        this.loading = true
        this.$refs.postForm.validate((valid, fields) => {
          // 判断规则是否验证通过
          if (valid) {
            const role = Object.assign({}, this.postForm)
            // 添加角色菜单和权限规则
            role.menus = this.$refs.menuTree.getCheckedKeys(false)
            role.half_menus = this.$refs.menuTree.getHalfCheckedKeys()
            role.rules = this.$refs.ruleTree.getCheckedKeys(true)
            // console.log(role)
            if (!this.isEdit) {
              addAuthRole(role).then(response => {
                this.$notify({
                  title: '成功',
                  message: response.msg,
                  type: 'success',
                  duration: 2000
                })
                this.$emit('ended')
              }).catch(() => {
                this.loading = false
              })
            } else {
              role.id = this.id
              editAuthRole(role).then(response => {
                this.$notify({
                  title: '成功',
                  message: response.msg,
                  type: 'success',
                  duration: 2000
                })
                this.$emit('ended')
              }).catch(() => {
                this.loading = false
                this.toDefault()
              })
            }
          } else {
            this.loading = false
            for (const key in fields) {
              if (fields.hasOwnProperty(key)) {
                const element = fields[key]
                this.$message({
                  message: element[0].message,
                  type: 'error',
                  duration: 2000
                })
                return false
              }
            }
          }
        })
      }
      // console.log('提交表格内容')
    },
    async getTreeData() {
      const menuTreeData = await getMenuElementTreeData()
      const ruleTreeData = await getRuleElementTreeData()
      // console.log(menuTreeData)
      this.postForm.menus = menuTreeData.data.select
      this.menuTreeData = menuTreeData.data.tree
      this.postForm.rules = ruleTreeData.data.select
      this.ruleTreeData = ruleTreeData.data.tree
      // console.log(this.menuTreeData)

      this.getRoleByID()

      this.$nextTick().then(() => {
        this.changeTreeClass()
      })
    },
    getRoleByID() {
      if (this.id !== 0) {
        getAuthRoleByID(this.id).then(response => {
          if (!response.data || response.data.length === 0) {
            this.isEdit = false
            return
          }
          this.isEdit = true
          const {
            title,
            name,
            status,
            menus,
            rules
          } = response.data
          this.postForm = {
            title,
            name,
            status
          }
          this.postForm.menus = (menus && menus.length > 0) ? menus : this.postForm.menus
          this.postForm.rules = (rules && rules.length > 0) ? rules : this.postForm.rules
        }).catch(() => {
          this.isEdit = false
        })
      } else {
        this.isEdit = false
      }
    },
    toDefault() {
      this.$refs.postForm.resetFields()
      this.loading = false
    },
    renderTreeContent(h, { node, data }) {
      // console.log(node, data)

      let className = ''
      // 用end_node来判断是否为最后一个节点，如何是最后一个节点则是进行横向处理
      if (data.end_node && !data.children) {
        className = 'especially'
      }

      return (
        // 在需要做横向排列的模块做标记
        <span class={className}>{data.label}</span>
      )
    },
    changeTreeClass() {
      // 找到之前做标记的class
      var classDomList = document.getElementsByClassName('especially')

      // 改变样式
      for (let i = 0; i < classDomList.length; i++) {
        classDomList[i].parentNode.style.cssText = 'float:left'
        classDomList[i].parentNode.className = 'el-tree-node__content tree-option-wrapper'
        // console.log(classDomList[i].parentNode.parentNode.parentNode.className)
        if (classDomList[i].parentNode.parentNode.parentNode.className.indexOf('el-tree-node__children') !== -1) {
          classDomList[i].parentNode.parentNode.parentNode.style.marginLeft = '40px'
        }
      }
    }
  }
}
</script>

<style lang="scss">
.form-data {
  margin-top: 10px;
}
.tree-option-wrapper {
  padding: 0 !important;
}
</style>
